
import { createRouter, createWebHashHistory } from "vue-router";
import { getTokenAUTH } from '@/utils/auth';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: '默认路径',
      redirect: '/login'
    },
    {
      path: '/login',
      name: '登录',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: true },
    },

    {
      path: '/contact/add/:uid',
      component: () => import('@/components/contact/AddContact.vue'),
    },
    {
      path: '/main',
      redirect: "/chat",
      component: () => import('@/views/home/Home.vue'),
      children: [
        {
          path: '/chat',
          component: () => import('@/views/chat/ChatContainer.vue'),
          children: [
            {
              path: '/chat/:id',
              component: () => import('@/components/chat/Chat.vue'),
            },
          ],
        },
        {
          path: '/contact',
          component: () => import('@/views/contact/ContactBook.vue'),
          children: [
            {
              path: '/contact/newfriend/:id',
              component: () => import('@/components/newfriend/NewFriend.vue'),
            },
            {
              path: '/contact/friend/:id',
              component: () => import('@/components/contact/ContactInfo.vue'),
            },
            {
              path: '/contact/offiaccount/:id',
              component: () => import('@/components/offiaccount/OfficalAccount.vue'),
            },
            {
              path: '/contact/groupchat/:id',
              component: () => import('@/components/groupchat/GroupChat.vue'),
            },

          ],
        },
        {
          path: '/collection',
          component: () => import('@/views/collection/Collection.vue'),
          children: [
            {
              path: '/collection/collectionlist',
              component: () => import('@/components/collection/CollectionList.vue'),
            },
          ],
        },

      ]
    },
    {
      path: '/friendmoment',
      component: () => import('@/views/friendmoment/FriendMoment.vue'),
      children: [

      ],
    },
  ],
});

// 阻止页面跳转（解决鼠标快捷键误触前进后退）
let navigateDisabled = false;

window.addEventListener('mouseup', event => {
  if ([4, 5].includes(event.which)) {
    navigateDisabled = true;
  } else {
    navigateDisabled = false;
  }
});

router.beforeEach((to, from, next) => {
  // 阻止鼠标快捷键引起的前进后退
  if (navigateDisabled) {
    next(false);

    navigateDisabled = false;
    return;
  }

  // 从localstorage获取token
  const token = getTokenAUTH();
  if (to.meta.requiresAuth && !token) {
    next('/login');
  } else {
    next();
  }
});

export default router;